
//
// 101121 - AH - Created.
// 101122 - AH - Made abstract.
//

package org.soekrat.engine.io;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *   Base class for objects that converts attribute values to
 *   {@link String} representations.
 * </p>
 * <p>
 *   For a named attribute {@code this} delegates to an
 *   {@link AttributeValueToString} object.   
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
public abstract class AttributeValuesToString 
{
  private Map<String, AttributeValueToString> m_handlers=
    new HashMap<String, AttributeValueToString>();
  
  /**
   * <p>
   *   Creates with no 
   *   {@link AttributeValueToString} handlers, use
   *   {@link #add(AttributeValueToString)} to add handlers.
   * </p>
   */
  protected AttributeValuesToString(){}
  
  /**
   * <p>
   *   Adds handler.
   * </p>
   * @param h Object that handles producing 
   *          {@link String} representations for
   *          {@link AttributeValueToString#getAttributeName() named} attribute 
   *          value.
   * @return {@code this}.
   */
  protected final AttributeValuesToString add(AttributeValueToString h)
  {
    if (h==null)
    {
      throw new NullPointerException("h");
    }
    
    m_handlers.put(h.getAttributeName(), h);
    return this;
  }
  
  /**
   * <p>
   *   Gets 
   *   {@code String} representation of attribute value.
   * </p>
   * <p>
   *   If there is no
   *   {@link AttributeValueToString} handler for named resource and 
   *   {@code value} is not {@code null} {@code value.toString()} is returned.
   * </p>
   * @param name  Attribute name.
   * @param value Attribute value. If {@code null} the "null" is returned.
   * @return {@code String} representation.
   */
  public final String toString(String name, Object value)
  {
    if (name==null)
    {
      throw new NullPointerException("name");
    }
    
    if (value==null) return "null";
    
    AttributeValueToString h=m_handlers.get(name);
    return h==null ? value.toString() : h.toString(value);
  }
  
}
